package com.yd;

import net.sf.json.JSONObject;
import org.apache.http.ProtocolException;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.net.ssl.HttpsURLConnection;
import java.io.*;
import java.net.ConnectException;
import java.net.MalformedURLException;
import java.net.URL;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/wx")
public class WxAuthController {

    private Map<Object,Object> map = null;

    @RequestMapping("/login")
    public Map<Object,Object> Login( String code) {
        map = new HashMap<>();
        try {
            String openid = "";
            String session_key ="";
            String errcode = "";
            String errmsg ="";
            //填写你小程序的appid 和 secret ,  还有前端传给你的code ,最后一个参数是固定的
            String token_url = " https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + "wx4c1b026545f7722f" + "&secret=" + "d785f024e0d32d892a30f13e613d51ae" + "&code=" + code + "&grant_type=authorization_code";
            JSONObject access_token = httpsRequestToJsonObject(token_url, "GET", null);
            if (access_token.getString("openid") != "" || access_token.getString("openid") != null && access_token.getString("session_key") != null || access_token.getString("session_key") != ""){
                //openid    string    用户唯一标识 这个就是你微信用户标识
                openid = access_token.getString("openid");//oWbGv4v0rIuufwtRnnaWCixSLjjE oWbGv4v0rIuufwtRnnaWCixSLjjE
                System.err.println(openid);
                map.put("openid",openid);
            }

        } catch (Exception e) {

        }
        return  map;
    }


    public static JSONObject httpsRequestToJsonObject(String requestUrl, String requestMethod, String outputStr) {
        JSONObject jsonObject = null;
        try {
            StringBuffer buffer = httpsRequest(requestUrl, requestMethod, outputStr);
            jsonObject = JSONObject.fromObject(buffer.toString());
        } catch (ConnectException ce) {
            System.err.println("请求连接超时"+ce);
        } catch (Exception e) {
            System.err.println("https请求异常：" + e.getMessage());
        }
        return jsonObject;
    }

    private static StringBuffer httpsRequest(String requestUrl, String requestMethod, String output)
            throws NoSuchAlgorithmException, NoSuchProviderException, KeyManagementException, MalformedURLException,
            IOException, ProtocolException, UnsupportedEncodingException {
        URL url = new URL(requestUrl);
        HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
        connection.setDoOutput(true);
        connection.setDoInput(true);
        connection.setUseCaches(false);
        connection.setRequestMethod(requestMethod);
        if (null != output) {
            OutputStream outputStream = connection.getOutputStream();
            outputStream.write(output.getBytes("UTF-8"));
            outputStream.close();
        }
        // 从输入流读取返回内容
        InputStream inputStream = connection.getInputStream();
        InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
        BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
        String str = null;
        StringBuffer buffer = new StringBuffer();
        while ((str = bufferedReader.readLine()) != null) {
            buffer.append(str);
        }
        bufferedReader.close();
        inputStreamReader.close();
        inputStream.close();
        inputStream = null;
        connection.disconnect();
        return buffer;
    }


}
